package cn.simple.filetools.poi.excel.support;

import cn.simple.filetools.exception.WriteExcelException;
import cn.simple.filetools.poi.excel.PoiExcelReadListener;
import cn.simple.filetools.poi.excel.PoiExcelWriteProcessor;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author jiangjinjian
 * @date 2024/8/28 10:33
 * @description excel处理器
 */
public class ExcelHandler<T> {

    private final PoiExcelReadListener<T> readListener;

    private final PoiExcelWriteProcessor<T> writeProcessor;

    private ExcelHandler(PoiExcelReadListener<T> readListener, PoiExcelWriteProcessor<T> writeProcessor) {
        this.readListener = readListener;
        this.writeProcessor = writeProcessor;
    }

    public static <R> ExcelHandler<R> create(PoiExcelReadListener<R> readListener, PoiExcelWriteProcessor<R> writeProcessor) {
        return new ExcelHandler<>(readListener, writeProcessor);
    }

    public ExcelHandler<T> read(InputStream is) {
        this.readListener.readByAnnotation(is);
        return this;
    }

    public List<T> getData() {
        return this.readListener.getData();
    }

    public List<Map<Integer, String>> getHead() {
        return this.readListener.getHeadMapList();
    }

    public OutputStream write() {
        return write(this.readListener.getData());
    }

    public OutputStream write(List<T> data) {
        return this.writeProcessor.write(data);
    }

    public void writeToRes(List<T> data, HttpServletResponse response) {
        try (ByteArrayOutputStream os = (ByteArrayOutputStream) write(data)) {
            response.getOutputStream().write(os.toByteArray());
        } catch (IOException e) {
            throw new WriteExcelException(e);
        }
    }
}
